package system
import(
	"container/list"
	"runtime"
	"os"
	"fmt"
	"bytes"
	"mime"
	"os/user"
)
const (
	//获取系统属性需要的名称
	PROPERTY_PATH_SEPARATOR="PathSeparator"
	PROPERTY_USER="User"
	PROPERTY_HOST_NAME="HostName"
	PROPERTY_OS="OS"
	PROPERTY_LIST_MAX=128
)
var OSName=runtime.GOOS
type (
	//系统的实例
	SystemInstance interface{
		GetUser() (*user.User,os.Error)
		GetHostName() string
		GetDriveList() string
		GetFileInfo(v string) *SystemFile
		Open(path string) (*os.File,os.Error)
	}
	SystemFile struct{
		IsFolder,IsChar,IsRegular bool
		Name,Path,MimeType,Error	string
		Children []SystemFile
		Permission uint32
		Size int64
	}
)
var systemInstance SystemInstance
//通过保存系统属性的列表，获取并返回系统属性
func GetProperty(list *list.List) map[string]string{
	property:=make(map[string]string)
	systemInstance=ensureSystemInstance()
	for e:=list.Front();;{
		s:=e.Value
		p:=s.(string)
		switch p {
			case PROPERTY_PATH_SEPARATOR:
				property[p]=fmt.Sprintf("%c",os.PathSeparator)
			case PROPERTY_USER:
				u,err:=systemInstance.GetUser()
				if err!=nil{
					property["Error"]=err.String()
				}else{
					property["HomeFolder"]=u.HomeDir
					property["User"]=u.Name
				}
			case PROPERTY_OS:
				property[p]=OSName
				if OSName=="windows"{
					property["DriveList"]=systemInstance.GetDriveList()
				}
			case PROPERTY_HOST_NAME:
				property[p]=systemInstance.GetHostName()
		}
		e=e.Next()
		if e==nil{
			break
		}
	}
	return property
}
//新建一个系统实例
func NewSystemInstance() SystemInstance{
	os:=OSName
	if(os=="windows"){
		return &Windows{}
	}else if (os=="linux"){
		return &Linux{}
	}
	return nil
}
func GetFileInfo(v string) *SystemFile{
	systemInstance=ensureSystemInstance()
	return systemInstance.GetFileInfo(v)
}
func ensureSystemInstance() SystemInstance{
	if systemInstance==nil{
		systemInstance=NewSystemInstance()
	}
	return systemInstance
}
func Open(path string) (*os.File,os.Error){
	systemInstance=ensureSystemInstance()
	return systemInstance.Open(path)
}
//获取文件的类型
func GetContentType(path string) string{
	pathByte:=bytes.ToLower([]byte(path))
	i:=bytes.LastIndex(pathByte,[]byte("."))
	if i<0{i=0}
	t:= mime.TypeByExtension(string(pathByte[i:]))
	if t==""{
		return "text/pain"
	}
	return t
}
